package com.weifeng.getandpostdemo.https;


import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustAllStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;


public class PostHttps {
    private static final String[] PROTOCOLS = new String[] { "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2" };

    public static PoolingHttpClientConnectionManager poolCon() {
        try {
            SSLContext sc = new SSLContextBuilder().loadTrustMaterial(new TrustAllStrategy()).build();
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sc,PROTOCOLS, null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", ssf)
                    .build();
            PoolingHttpClientConnectionManager poolCon = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            poolCon.setMaxTotal(200);
            return poolCon;
        }catch (Exception e){
            System.out.println(e);
            return null;
        }

    }

    public static void main(String[] args) throws Exception{

        CloseableHttpClient aDefault = HttpClients.custom().setConnectionManager(poolCon()).build();

//        HttpGet httpGet = new HttpGet("https://localhost:443/responsejson");

        HttpGet httpGet = new HttpGet("http://localhost:8080/responsejson");

        CloseableHttpResponse execute = aDefault.execute(httpGet);

        System.out.println(EntityUtils.toString(execute.getEntity()));

    }

}
